package server.loader;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import server.utils.WebResourceUtils;

public class WebappClassLoader  extends URLClassLoader {


    private Set<URL> urlList = new HashSet<>();
    private boolean hasInmportUrls = false;



    public WebappClassLoader(ClassLoader parent) {
        super(new URL[0], parent);

    }

    public void loadClassPath(String path) throws MalformedURLException {
       File file = new File(path);
       URL url = file.toURI().toURL();
        urlList.add(url);
    }
    public  void loadJarPath(String path) throws MalformedURLException {
        urlList.addAll(WebResourceUtils.loadClassPathUrls(new File(path)));
    }

    /**
     * 将当前的所有url加载到classloader中
     */
    public void loadUrls(){
        if(hasInmportUrls){
         return;
        }
        Iterator<URL> iterator = urlList.iterator();
        while(iterator.hasNext()){
            this.addURL(iterator.next());
        }
        hasInmportUrls = true;
    }

//    public Class loadClass(String className) throws ClassNotFoundException {
//        loadUrls();
//        return this.loadClass(className,false);
//    }


}
